module TableFunction (TFunction, getValue, construct) where

import Data.Map
import qualified Data.Map as Map
import Data.Maybe

type TFunction = Map Double Double

construct :: [(Double, Double)] -> TFunction
construct x = fromList x

getValueZero f x = fromMaybe 0.0 (getValue f x)
        
getValue :: TFunction->Double->Maybe Double
getValue f x = findValue x (splitLookup x f)

findValue :: Double->(TFunction, Maybe Double, TFunction)->Maybe Double
findValue x (_, Just v, _) = Just v
findValue x (l, Nothing, r) 
        | Map.null l = Nothing
        | Map.null r = Nothing
findValue x (l, Nothing, r) = Just (evaluateLinear x [(findMax l),(findMin r)])
                                             
evaluateLinear :: Double->[(Double,Double)]->Double
evaluateLinear x [(x0, y0), (x1, y1)] = y0 + (y1-y0)/(x1-x0)*(x-x0)
evaluateLinear x _ = undefined